package com.bridgetree.jubaocrm.ui;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.LoginInterface;

/**
 * 修改密码
 */
public class EditPasswordActivity extends Activity {
	private final String TAG = "EditPasswordActivity";
	private Context mContext;
	private LoginInterface mLoginInterface;
	private InputMethodManager mInputMethodManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_edit_password);
		mContext = this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}

		mInputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);

		if (intent.getExtras() != null) {
			mLoginInterface = (LoginInterface) intent.getExtras().getSerializable(
					"LoginInterface");
		}

		findViewById(R.id.main_edit_password_RelativeLayout_back)
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						finish();
					}
				});

		findViewById(R.id.main_edit_password_ok).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						getEditPassword();
					}
				});
	}

	private void openDailogs(String title, String content) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content)
				.setPositiveButton("确定", null).show();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}

	private void getEditPassword() {
		EditText xm_lxr_ed_password = (EditText) findViewById(R.id.xm_lxr_ed_password);
		EditText xm_lxr_ed_password2 = (EditText) findViewById(R.id.xm_lxr_ed_password2);
		String context = xm_lxr_ed_password.getText().toString();
		String context2 = xm_lxr_ed_password2.getText().toString();
		int contextSize = context.length();
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailogs("网络提示", "网络未连接,请连接网络！");
		} else if (!context.equals(context2)) {
			openDailogs("输入提示", "内容必须一致");
		} else if (contextSize < 6 || contextSize > 20) {
			openDailogs("输入提示", "内容必须是6-20个字符");
		} else {
			final ProgressDialog progressDialog=ProgressDialogUtil.show(mContext);
			//password=123456
			//&user_id=581c3768b5f74d4097ae78ec8d58b8c9
			//&token=7f93e33e604f4cf2a9971be45f86eb79
			//&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl
			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("password", context);
			mMap.put("user_id", mLoginInterface.getUser_id());
			mMap.put("token", mLoginInterface.getToken());
			mMap.put("validation", CRMUserBaseInfo.kValication);
			String URL = Network.API_DOMAIN + "/password";

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								System.out.println("密码修改  response=" + response);
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
											.toString();
									if (errors.equals("[]")) {
										Toast.makeText(mContext, "密码修改成功！",Toast.LENGTH_LONG).show();
										finish();
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
													.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
														.length(); i++) {
													JSONObject jsonObj2 = jsonArr
															.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
																.getString("desc");
														openDailogs("失败提示", desc);
														mLoginError
																.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
																.getString("value");
														mLoginError
																.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							ProgressDialogUtil.dissmis(progressDialog);
							Toast.makeText(mContext, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}

	}

}